# -*- coding: utf-8 -*-

from common.utils.adb_manager import AdbManager
from common.utils.common_functions import *
from common.utils.excel_read import ExcelRead


class AdbAndExcelManager:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            # 创建新的实例
            instance = super().__new__(cls)
            cls._instance = instance
        return cls._instance

    def __init__(self):
        # 判断实例是否已经初始化
        if not hasattr(self, 'authorization_time'):
            self.excel_read = ExcelRead()
            self.adb_manager = AdbManager()

    # 初始化测试参数
    def test_parameter_init(self):
        if self.excel_read.test_parameter_pos():
            print("\n*****************************************************************************\n")
            while True:
                device_identifier = self.excel_read.sheet2.cell(self.excel_read.row_device_identifier_pos + 1, 2).value
                if device_identifier is None or device_identifier.strip() == "":
                    device_identifier = get_string_input("请输入测试设备标识（例如：设备ip:端口、设备序列号）：")
                    self.adb_manager.connect_device(device_identifier)
                    if not self.adb_manager.is_connect_device(device_identifier):
                        print(f"请确认{device_identifier}设备是否存在")
                        continue
                else:
                    self.adb_manager.connect_device(device_identifier)
                    if not self.adb_manager.is_connect_device(device_identifier):
                        print(f"请确认{device_identifier}设备是否存在")
                        device_identifier = get_string_input("请输入测试设备标识（例如：设备ip:端口、设备序列号）：")
                        self.adb_manager.connect_device(device_identifier)
                        if not self.adb_manager.is_connect_device(device_identifier):
                            continue
                self.excel_read.device_identifier = device_identifier
                self.excel_read.update_sheet2_cell_value(self.excel_read.row_device_identifier_pos + 1, 2,
                                                         device_identifier)

                app_package_name = self.excel_read.sheet2.cell(self.excel_read.row_app_package_name_pos + 1, 2).value
                if app_package_name is None or app_package_name.strip() == "":
                    print(f"获取包名：adb -s {device_identifier} shell pm list packages -3")
                    app_package_name = get_string_input("请输入测试app包名（例如：com.test.test）：")
                    if not self.adb_manager.is_app_installed(device_identifier, app_package_name):
                        print(f"请确认{app_package_name}是否安装")
                        continue
                else:
                    if not self.adb_manager.is_app_installed(device_identifier, app_package_name):
                        print(f"请确认{app_package_name}是否安装")
                        print(f"获取包名：adb -s {device_identifier} shell pm list packages -3")
                        app_package_name = get_string_input("请输入测试app包名（例如：com.test.test）：")
                        if not self.adb_manager.is_app_installed(device_identifier, app_package_name):
                            continue
                self.excel_read.app_package_name = app_package_name
                self.excel_read.update_sheet2_cell_value(self.excel_read.row_app_package_name_pos + 1, 2,
                                                         app_package_name)

                app_startup_activity = self.excel_read.sheet2.cell(self.excel_read.row_app_startup_activity_pos + 1, 2)\
                    .value
                if app_startup_activity is None or app_startup_activity.strip() == "":
                    print(f"app运行时，获取当前活动页面：adb -s {device_identifier} shell dumpsys activity activities "
                          f"| grep {app_package_name}")
                    app_startup_activity = get_string_input("请输入app活动名（例如：com.test.test.MainActivity）：")
                    if not self.adb_manager.is_app_running(device_identifier, app_package_name):
                        self.adb_manager.start_app(device_identifier, app_package_name, app_package_name)
                        if not self.adb_manager.is_app_running(device_identifier, app_package_name):
                            continue
                else:
                    if not self.adb_manager.is_app_running(device_identifier, app_package_name):
                        self.adb_manager.start_app(device_identifier, app_package_name, app_startup_activity)
                        if not self.adb_manager.is_app_running(device_identifier, app_package_name):
                            print(f"请确认app是否运行，app活动名{app_startup_activity}是否正确")
                            print(f"app运行时，获取当前活动页面：adb -s {device_identifier} shell dumpsys activity activities "
                                  f"| grep {app_package_name}")
                            app_startup_activity = get_string_input("请输入app活动名（例如：com.test.test.MainActivity）：")
                            if not self.adb_manager.is_app_running(device_identifier, app_package_name):
                                self.adb_manager.start_app(device_identifier, app_package_name, app_package_name)
                                if not self.adb_manager.is_app_running(device_identifier, app_package_name):
                                    continue
                self.excel_read.app_startup_activity = app_startup_activity
                self.excel_read.update_sheet2_cell_value(self.excel_read.row_app_startup_activity_pos + 1, 2,
                                                         app_startup_activity)

                script = self.excel_read.sheet2.cell(self.excel_read.row_script_pos + 1, 2).value
                if script is None:
                    script = get_string_input("请输入测试脚本名称（例如：测试脚本.exe）：")
                    if not script.endswith(".exe"):
                        print(f"输入参数{script}错误，请重新输入")
                        continue
                else:
                    if not script.endswith(".exe"):
                        script = get_string_input("请输入测试脚本名称（例如：测试脚本.exe）：")
                        if not script.endswith(".exe"):
                            print(f"输入参数{script}错误，请重新输入")
                            continue
                self.excel_read.script = script
                self.excel_read.update_sheet2_cell_value(self.excel_read.row_script_pos + 1, 2, script)

                crash_number = self.excel_read.sheet2.cell(self.excel_read.row_crash_number_pos + 1, 2).value
                if crash_number is None:
                    crash_number = get_integer_input("请输入app连续崩溃次数上限：")
                else:
                    try:
                        crash_number = int(crash_number)
                    except ValueError:
                        crash_number = get_integer_input("请输入app连续崩溃次数上限：")
                self.excel_read.crash_number = crash_number
                self.excel_read.update_sheet2_cell_value(self.excel_read.row_crash_number_pos + 1, 2, crash_number)

                crash_logs_number = self.excel_read.sheet2.cell(self.excel_read.row_crash_logs_number_pos + 1, 2).value
                if crash_logs_number is None:
                    crash_logs_number = get_integer_input("请输入获取app崩溃日志数量：")
                else:
                    try:
                        crash_logs_number = int(crash_logs_number)
                    except ValueError:
                        crash_logs_number = get_integer_input("请输入获取app崩溃日志数量：")
                self.excel_read.crash_logs_number = crash_logs_number
                self.excel_read.update_sheet2_cell_value(self.excel_read.row_crash_logs_number_pos + 1, 2,
                                                         crash_logs_number)

                monitor_crash_interval = self.excel_read.sheet2\
                    .cell(self.excel_read.row_monitor_crash_interval_pos + 1, 2).value
                if monitor_crash_interval is None:
                    monitor_crash_interval = get_integer_input("请输入app监听时间间隔ms：")
                    if monitor_crash_interval < 100:
                        print("app监听时间间隔至少100ms")
                        monitor_crash_interval = 100
                else:
                    try:
                        monitor_crash_interval = int(monitor_crash_interval)
                        if monitor_crash_interval < 100:
                            print("app监听时间间隔至少100ms")
                            monitor_crash_interval = 100
                    except ValueError:
                        monitor_crash_interval = get_integer_input("请输入app监听时间间隔ms：")
                        if monitor_crash_interval < 100:
                            print("app监听时间间隔至少100ms")
                            monitor_crash_interval = 100
                self.excel_read.monitor_crash_interval = monitor_crash_interval
                self.excel_read.update_sheet2_cell_value(self.excel_read.row_monitor_crash_interval_pos + 1, 2,
                                                         str(monitor_crash_interval))

                click_interval = self.excel_read.sheet2.cell(self.excel_read.row_click_interval_pos + 1, 2).value
                if click_interval is None:
                    click_interval = get_integer_input("请输入测试步骤点击时间间隔ms：")
                    if click_interval < 100:
                        print("测试步骤点击时间间隔至少100ms")
                        click_interval = 100
                else:
                    try:
                        click_interval = int(click_interval)
                        if click_interval < 100:
                            print("测试步骤点击时间间隔至少100ms")
                            click_interval = 100
                    except ValueError:
                        click_interval = get_integer_input("请输入测试步骤点击时间间隔ms：")
                        if click_interval < 100:
                            print("测试步骤点击时间间隔至少100ms")
                            click_interval = 100
                self.excel_read.click_interval = click_interval
                self.excel_read.update_sheet2_cell_value(self.excel_read.row_click_interval_pos + 1, 2,
                                                         str(click_interval))
                print("\n*********************************测试参数****************************************\n")
                print(f"{self.excel_read.row_device_identifier_title}: {device_identifier}")
                print(f"{self.excel_read.row_app_package_name_title}: {app_package_name}")
                print(f"{self.excel_read.row_app_startup_activity_title}: {app_startup_activity}")
                print(f"{self.excel_read.row_script_title}: {script}")
                print(f"{self.excel_read.row_crash_number_title}: {crash_number}")
                print(f"{self.excel_read.row_crash_logs_number_title}: {crash_logs_number}")
                print(f"{self.excel_read.row_monitor_crash_interval_title}: {monitor_crash_interval}")
                print(f"{self.excel_read.row_click_interval_title}: {click_interval}")
                print("\n*********************************测试参数****************************************\n")
                break
        else:
            exit_program("请在testdata/data_files/app_test.xlsx表二的列1，列2分别填写缺少参数与数据")

